<?php

defined('_JEXEC') or die();

jimport('joomla.application.component.model');
require_once JPATH_COMPONENT.DS.'helpers'.DS.'extensionsHelper.php';

class Easiv2adminModelManageExtensions extends JModel {

	var $db;
	var $repoDir;
	var $extensionsHelper;
	var $extensionNames = array();
	var $parser;
	var $instances;
	var $packages;

	function __construct() {
		parent::__construct();

		$this->repoDir = 'repository';
		$this->extensionsHelper = new ExtensionsHelper($this->repoDir);
		$this->parser = new XmlParser();
		
		$this->db =& JFactory::getDBO();
		$this->db->setQuery("SELECT * FROM #__easiv2_instances ORDER BY id");
		$result = $this->db->loadObjectList();
		
		$this->instances = array();
		
		for($i=0; $i<count($result); $i++) {
			$this->instances[$i] = $result[$i];
		}
		
		$this->scanRepository();
	}
	
	/**
	 * function which scans repository for extension archives. not existing extensions will be deleted from database.
	 */
	function scanRepository() {
		if(!JFolder::exists(JPATH_COMPONENT.DS.$this->repoDir)) {
			JFolder::create(JPATH_COMPONENT.DS.$this->repoDir);
		}
		
		$this->packages = JFolder::files(JPATH_COMPONENT.DS.$this->repoDir, ".zip");
		
		//unpack	
		foreach($this->packages as $package) {
			$this->extensionNames[] = $this->extensionsHelper->unpack(JPATH_COMPONENT.DS.$this->repoDir.DS.$package);
		}
		
		$this->updateDatabase();		
	}
	
	function updateDatabase() {
		$this->db->setQuery("SELECT packagefile, xmlFile FROM #__easiv2");
		$dbPackages = $this->db->loadObjectList();

		foreach($dbPackages as $dbPackage) {
			$delete = true;
				
			foreach($this->packages as $package) {
				//echo "comparing DB ".str_ireplace("|", DS, $dbPackage->packagefile)." with ".JPATH_COMPONENT.DS.$this->repoDir.DS.$package."<br>";
				if(str_ireplace("|", DS, $dbPackage->packagefile) == JPATH_COMPONENT.DS.$this->repoDir.DS.$package) {
					$delete = false;
				}
			}
				
			if($delete) {
				$this->db->setQuery("DELETE FROM #__easiv2 WHERE packagefile ='".$dbPackage->packagefile."'");
				$this->db->query();

				if(JFile::exists(JPATH_COMPONENT.DS.$this->repoDir.DS.'manifest'.DS.$dbPackage->xmlFile)) {
					JFile::delete(JPATH_COMPONENT.DS.$this->repoDir.DS.'manifest'.DS.$dbPackage->xmlFile);
				}
			}
		}
	}
	
	function getExtensions() {
		$this->db->setQuery("SELECT extension, version FROM #__easiv2");
		$result = $this->db->loadObjectList();
		
		return $result;
	}
	
	function getLocalInstallStatus() {
		/*
		 * Array where install status is saved
		 */
		$installStatus = array();

		for($i = 0; $i < count($this->extensionNames); $i++) {
			$status = $this->extensionsHelper->isInstalled($this->extensionNames[$i]);
			$extensionName = $this->extensionNames[$i];
			$installStatus[(string)$extensionName] = $status;
		}

		return $installStatus;
	}
	
	function getRemoteInstanceObjects() {
		return $this->instances;
	}

	function getRemoteInstallStatus() {

		$request_method = 'manageExtensions.isExtensionInstalled';
		
		/*
		 * Array in which the install information from remote instance will be saved
		 */
		$installStatus = array();
		$instancesInstallArray = array();
		
		if(count($this->instances > 0)) {
			
			for($i=0;$i < count($this->instances); $i++) {				
								
				$db =& JFactory::getDBO();				
				$db->setQuery('SELECT extension FROM #__easiv2');
				$result = $db->loadObjectList();
		
				foreach($result as $r) {
					$request_param = xmlrpc_encode($r->extension);
		
					$postdata = http_build_query(
						array(
					        'extension' => $request_param,
						)
					);
		
					$opts = array('http' =>	array(
					        'method'  => 'POST',
					        'header'  => 'Content-type: application/x-www-form-urlencoded',
							'content' => $postdata
						)
					);
		
					$context  = stream_context_create($opts);
					
					$instanceUrl = $this->instances[$i]->http_address;
					$response = file_get_contents($instanceUrl."/index.php?option=com_easiv2&task=".$request_method."&format=xmlrpc", false, $context);
					
					$installStatus[$r->extension] = $response;
				}
				
				$instancesInstallArray[(string) $this->instances[$i]->name] = $installStatus;		
				
			}
			
			return $instancesInstallArray;
		}
		else {
			return null;
		}
	}
}